package com.house365.core.view.menu;

import java.util.ArrayList;
import java.util.Currency;
import java.util.List;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.house365.core.R;
import com.house365.core.view.common.ScrollerView;
/**
 * re-write py
 * 提供通用Tab-bar切换菜单组件
 * 通用toolbar 切换菜单，外部可以通过注册 FlowTabBarListener 监听tab切换状况
 * 布局文件示例
 * <com.house365.core.view.menu.TabBarMenu
            android:id="@+id/tabbar_view"
            android:layout_width="280dip" //宽度和、高度必须为dp、dip
            android:layout_height="30dip"//
            android:layout_centerInParent="true"
            android:visibility="visible"
            android:background="@drawable/tab_header_bg" //该空间本身背景
            app:tab_color="@android:color/white" //tab每个子菜单文字颜色
            app:tab_selected_background="@drawable/tab_header_selected"//tab每个子菜单被选中背景
            app:tab_selected_color="@android:color/white"//tab每个子菜单被选中颜色
            app:tab_text="@string/text_me_tab_title" /> //tab每个子菜单文字，以逗号隔开eg：<string name="text_me_tab_title">申请,咨询,收藏</string>
     @TODO,后期实现每个子菜单自定义view格式       
 */
public class TabBarMenu extends RelativeLayout {
	private Context mContext;
	private int tab_num;
	private int tab_selected_background;
	private int tab_color;
	private int tab_selected_color;
	private float tab_bar_width;
	private float tab_bar_height;
	private float tab_textsize;
	private String tab_text; //String split by ,
	private ScrollerView tabselectedImage; //Background selected
	private String[] tab_text_arrays;
	private int tabBarWitdh = 0;
	private List<TextView> tabTitleViewList = new ArrayList<TextView>();
	private int currIndex = 0;//current selected index
	private GestureDetector mGesture = null;	
	private TabBarChangeListener tabBarChangeListener;
    private boolean mBringToFront;
    
	/**
	 * 延迟动画控制
	 */
	private boolean mAnimating = false;
	//动画执行结束
	private final int MSG_ANIMATION_END =2000;
	private final int MSG_ANIMATION_START =1000;
	private int animationFactor =5;//每个pix移动的时间
	private int  lastX;
	private Handler animatingHandler =new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case MSG_ANIMATION_END:
					mAnimating = false;
					//修正一下位置
					int currentX = currIndex * tabBarWitdh;
					int scrollX = Math.abs(tabselectedImage.getScrollX());
					if(currentX != scrollX){
						//需要修正
						tabselectedImage.beginScroll(scrollX - currentX,0, 30);
					}
					setCurrentStyle();
					if(tabBarChangeListener != null){
						tabBarChangeListener.onChangeAfter(currIndex);
					}
					break;
				case MSG_ANIMATION_START:
					mAnimating = true;
					if(tabBarChangeListener != null){
						tabBarChangeListener.onChangeBefore(currIndex,(Integer)msg.obj);
					}
					break;	
			
			}
		}
	};
	
	
	
	public TabBarMenu(Context context) {
		super(context);
		this.mContext = context;
	}

	public TabBarMenu(Context context, AttributeSet attrs) throws Exception {
		super(context, attrs);
		this.mContext = context;
		initAttributes(context,attrs);
		initContent(context);
	}

	public TabBarMenu(Context context, AttributeSet attrs, int defStyle) throws Exception {
		super(context, attrs, defStyle);
		this.mContext = context;
		initAttributes(context,attrs);
		initContent(context);
	}
	/**
	 * 获取配置信息
	 * @param context
	 * @param attributeSet
	 * @throws Exception
	 */
	private void initAttributes(Context context,AttributeSet attributeSet) throws Exception {
		
		String layoutwith = attributeSet.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_width");
		String layoutheight = attributeSet.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_height");
		if(!isDip(layoutwith) || !isDip(layoutheight)){
			throw  new Exception("layout_width or layout_height muse be dip");
		}
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics dm = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(dm);
		
		tab_bar_width = getPixOfDip(dm,layoutwith);
		tab_bar_height =getPixOfDip(dm,layoutheight);
//		tab_bar_width = styledAttrs.getDimension(R.styleable.FlowTabBarView_tab_bar_width, 0);
//		tab_bar_height = styledAttrs.getDimension(R.styleable.FlowTabBarView_tab_bar_height, 0);
		
		
		TypedArray styledAttrs = mContext.obtainStyledAttributes(attributeSet,
				R.styleable.FlowTabBarView);
		tab_selected_background = styledAttrs.getResourceId(
				R.styleable.FlowTabBarView_tab_selected_background, 0);
		tab_color = styledAttrs.getColor(R.styleable.FlowTabBarView_tab_color, 0);
		tab_selected_color = styledAttrs.getColor(R.styleable.FlowTabBarView_tab_selected_color, 0);
		tab_textsize = styledAttrs.getFloat(
				R.styleable.FlowTabBarView_tab_textsize, 14);
		CharSequence tabtxt = styledAttrs
				.getText(R.styleable.FlowTabBarView_tab_text);
		if (null != tabtxt) {
			tab_text = tabtxt.toString();
			tab_text_arrays = init_tabtitle(tab_text);
		}
		if(tab_bar_height==0){
			tab_bar_height = LayoutParams.WRAP_CONTENT;
		}
	}
	private boolean isDip(String s){
		return s.indexOf("dip") >0 || s.indexOf("dp") >0;
	}
	private int getPixOfDip(DisplayMetrics dm,String s){
		s =s.replaceAll("dip","");
		s =s.replaceAll("dp","");
		
		return dip2pix(dm,Float.parseFloat(s));
	}
	public static int dip2pix(DisplayMetrics dm, float dipValue) {
		final float scale = dm.density;
		return (int) (dipValue * scale + 0.5f);
	}
	/**
	 * 初始化布局内容
	 * @param context
	 */
	private void initContent(Context context) {
		mGesture = new GestureDetector(mContext, new MyGestureListener());
		mGesture.isLongpressEnabled();
		this.setClickable(true);
		RelativeLayout.LayoutParams rootLayout = new RelativeLayout.LayoutParams((int)tab_bar_width,(int)tab_bar_height);
		this.setLayoutParams(rootLayout);
		tabBarWitdh = Math.round(tab_bar_width/tab_num);
		tabselectedImage = new ScrollerView(context);
		tabselectedImage.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		tabselectedImage.setBackgroundResource(android.R.color.transparent);
		ImageView imageView = new ImageView(context);
		imageView.setLayoutParams(new LayoutParams(tabBarWitdh,(int)tab_bar_height));
		imageView.setBackgroundResource(tab_selected_background);
		tabselectedImage.addView(imageView);
		this.addView(tabselectedImage);
		
		
		LinearLayout clayout = new LinearLayout(context);
		clayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		clayout.getWidth();
		clayout.setWeightSum(tab_num);
		this.addView(clayout);
		if (tab_num > 0) {
			for (int i = 0; i < tab_num; i++) {
				TextView tabTitle = new TextView(context);
				tabTitle.setLayoutParams(new LinearLayout.LayoutParams((int)tabBarWitdh,(int)tab_bar_height,1.0f));
				tabTitle.setTextColor(tab_color);
				tabTitle.setTextSize(tab_textsize);
				tabTitle.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL);
				tabTitle.setText(tab_text_arrays[i]);
				tabTitle.setId(i);
				clayout.addView(tabTitle);
				tabTitleViewList.add(tabTitle);
				if(i==currIndex){
					tabTitle.setTextColor(tab_selected_color);
				}else{
					tabTitle.setTextColor(tab_color);
				}
				
			}
			
		}
	}
	

	@Override
	protected void onAttachedToWindow()
	{
		super.onAttachedToWindow();
		ViewParent parent = getParent();
		if (parent != null && parent instanceof FrameLayout)
		{
			mBringToFront = true;
		}
	}
	
	private String[] init_tabtitle(String text) {
		String[] text_arrays = null;
		if (text != null) {
			if (text.indexOf(",") > 0) {
				text_arrays = text.split(",");
				tab_num = text_arrays.length;
			}
		}
		return text_arrays;
	}

	
	
	public int getCurrIndex() {
		return currIndex;
	}

	public void setCurrIndex(final int currIndex) {
		int currentX = this.currIndex * tabBarWitdh;
		int needMoveX = currIndex* tabBarWitdh;
		int duration = Math.abs(currentX -needMoveX)*animationFactor;
		animatingHandler.sendMessage(animatingHandler.obtainMessage(MSG_ANIMATION_START, duration));
		tabselectedImage.beginScroll(currentX -needMoveX,0,duration);
		animatingHandler.sendEmptyMessageDelayed(MSG_ANIMATION_END, duration);
		this.currIndex = currIndex;
	}

	public int getTabnum() {
		return tab_num;
	}


	public void setTabnum(int tabnum) {
		this.tab_num = tabnum;
	}

	public List<TextView> getTabTitleViewList() {
		return tabTitleViewList;
	}

	public void setTabTitle(String tabTitle) {
		tab_text_arrays = init_tabtitle(tabTitle);
		int i = 0;
		for (TextView tv : tabTitleViewList) {
			tv.setText(tab_text_arrays[i]);
			i++;
		}
	}


	public TabBarChangeListener getTabBarChangeListener() {
		return tabBarChangeListener;
	}

	public void setTabBarChangeListener(TabBarChangeListener tabBarChangeListener) {
		this.tabBarChangeListener = tabBarChangeListener;
	}

	public int getAnimationFactor() {
		return animationFactor;
	}

	public void setAnimationFactor(int animationFactor) {
		this.animationFactor = animationFactor;
	}


	//tabbar 变化事件监听
	public interface TabBarChangeListener{
		public void onChangeBefore(int position,int duration);
		public void onChangeAfter(int position);
	}
	
	/**
	 * 设置当前选中的item样式
	 */
	public void	setCurrentStyle(){
			int i=0;
			for (TextView tv : tabTitleViewList) {
				if(i==currIndex){
					tv.setTextColor(tab_selected_color);
				}else{
					tv.setTextColor(tab_color);
				}
				i++;
			}
	}
	/**
	 * 事件转发
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		if(mAnimating){
			//正在执行延迟动画，禁止用户执行touch操作
			return true;
		}
		int action = event.getAction();
		if (action == MotionEvent.ACTION_DOWN)
		{
			if (mBringToFront)
			{
				bringToFront();
			}
		}
		if (!mGesture.onTouchEvent(event))
		{
			if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL)
			{
				//当手指抬起来以后，还要判断，滚动条的位置
				
				currIndex = (int)Math.round((double)lastX/tabBarWitdh);
				
				int needMoveX = currIndex* tabBarWitdh;
				int duration = Math.abs(lastX -needMoveX)*animationFactor;
				animatingHandler.sendMessage(animatingHandler.obtainMessage(MSG_ANIMATION_START, duration));
				tabselectedImage.beginScroll( lastX -needMoveX,0,duration);
				lastX = lastX- needMoveX;
				animatingHandler.sendEmptyMessageDelayed(MSG_ANIMATION_END, duration);
			}
		}
		return super.dispatchTouchEvent(event);
	}

	

	
	/**
	 * 
	 * @author py
	 *
	 */
	private int ensureX(int x){
		int downX =x;
		if(downX<0){
			downX = 0;
		}
		if(downX> (tab_bar_width -tabBarWitdh)){
			downX = (int)(tab_bar_width -tabBarWitdh);
		}
		return downX;
	}
	/**
	 * 
	 * @author py
	 * 手势事件类
	 */
	class MyGestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
//			try { 
//				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE ) {
//					setPreviousPage();
//				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE) {
//					setNextPage();
//				}
//				return true;
//			} catch (Exception e) {
//				// nothing
//			}
			return false;
		}

	
		@Override
		public boolean onDown(MotionEvent e) {
			lastX = (int)(e.getX()- tabBarWitdh/2);
			lastX = ensureX(lastX);
			tabselectedImage.scrollTo(-lastX, 0);
			return false;
//			return true;
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			if (e2.getAction() == MotionEvent.ACTION_MOVE) {
				// float maxVelocity = height / animationDuration ;
				// long timestampDelta = System.currentTimeMillis()
				// - scrollTimestamp;
				// float maxScrollDelta = maxVelocity * timestampDelta ;
				// float currentScrollDelta = (e1.getY() - e2.getY())*0.05f;
				//
				// if (currentScrollDelta < maxScrollDelta * -1) {
				// currentScrollDelta = maxScrollDelta * -1;
				// }
				// if (currentScrollDelta > maxScrollDelta) {
				// currentScrollDelta = maxScrollDelta;
				// }
				lastX = Math.round(lastX -distanceX);

				// We can't scroll more than the width of our own frame layout
				lastX = ensureX(lastX);
				tabselectedImage.scrollTo(-lastX,0 );
			}
			return false;
		}

		@Override
		public void onShowPress(MotionEvent e) {
			super.onShowPress(e);
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			// TODO Auto-generated method stub
			return super.onSingleTapConfirmed(e);
		}
		
	}

}
